package com.roger.match.library.util;

import ohos.agp.animation.AnimatorValue;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.utils.Point;

import java.security.SecureRandom;


public class MatchItem extends AnimatorValue {

    public Point midPoint;
    public float translationX;
    public int index;

    private final Paint mPaint = new Paint();
    private float mFromAlpha = 1.0f;
    private float mToAlpha = 0.4f;
    private Point mCStartPoint;
    private Point mCEndPoint;

    /**
     * 初始化
     *
     * @param index     index
     * @param start     start
     * @param end       end
     * @param color     color
     * @param lineWidth lineWidth
     */
    public MatchItem(int index, Point start, Point end, int color, int lineWidth) {
        this.index = index;

        midPoint = new Point((start.getPointX() + end.getPointX()) / 2, (start.getPointY() + end.getPointY()) / 2);

        mCStartPoint = new Point(start.getPointX() - midPoint.getPointX(), start.getPointY() - midPoint.getPointY());
        mCEndPoint = new Point(end.getPointX() - midPoint.getPointX(), end.getPointY() - midPoint.getPointY());

        setColor(color);
        setLineWidth(lineWidth);
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.STROKE_STYLE);
    }

    /**
     * 设置线宽度
     *
     * @param width width
     */
    public void setLineWidth(int width) {
        mPaint.setStrokeWidth(width);
    }

    /**
     * 设置颜色
     *
     * @param color color
     */
    public void setColor(int color) {
        mPaint.setColor(new Color(color));
    }

    public void setCurveTransformation() {
        setCurveInternal(new TimelineCurve() {
            @Override
            public float getCurvedTime(float v) {
                float alpha = mFromAlpha;
                alpha = alpha + ((mToAlpha - alpha) * v);
                setAlpha(alpha);
                return v;
            }
        });
    }

    public void resetPosition(int horizontalRandomness) {
        SecureRandom random = new SecureRandom();
        int randomNumber = -random.nextInt(horizontalRandomness) + horizontalRandomness;
        translationX = randomNumber;
    }

    /**
     * 开启
     *
     * @param fromAlpha fromAlpha
     * @param toAlpha   toAlpha
     */
    public void start(float fromAlpha, float toAlpha) {
        mFromAlpha = fromAlpha;
        mToAlpha = toAlpha;
        super.start();
    }

    /**
     * 设置透明度
     *
     * @param alpha alpha
     */
    public void setAlpha(float alpha) {
        mPaint.setAlpha(alpha);
    }

    public void draw(Canvas canvas) {
        canvas.drawLine(mCStartPoint.getPointX(), mCStartPoint.getPointY(), mCEndPoint.getPointX(), mCEndPoint.getPointY(), mPaint);
    }
}